/**
 * 绑定回车焦点移动到下一个输入文本框中
 */
function bindEnterEvents() {
    function isIE() {
        return !!window.ActiveXObject || 'ActiveXObject' in window;
    }

    //  获取光标起始索引
    function getCursorIndex(element) {
        if (!isIE()) {
            return element.selectionStart;
        } else {
            let range = element.createTextRange();
            range.moveStart('character', -element.value.length);
            return range.text.length;
        }
    }

    $(document).on('keyup', 'input[type!="hidden"][readonly!="readonly"]:visible', function (e) {
        let inputs = $('input[type != "hidden"][readonly != "readonly"]:visible');
        let length = inputs.length;
        let currentIndex = inputs.index($(this));
        if (e.keyCode == 13) {
            if (length - 2 >= currentIndex)
                inputs.eq(currentIndex + 1).focus();
        } else if (e.keyCode == 37) {
            //  左箭头
            if (currentIndex - 1 >= 0) {
                if (getCursorIndex(this) === 0)
                    inputs.eq(currentIndex - 1).focus();
            }
        } else if (e.keyCode == 39) {
            //  右箭头
            if (length - 2 >= currentIndex) {
                if (getCursorIndex(this) >= $(this).val().length)
                    inputs.eq(currentIndex + 1).focus();
            }
        }
    })
}

/**
 * 绑定上下移动的功能键，用于Easyui编辑网格
 * @param ele
 * @param index
 */
function bindInputEvents(ele, index) {
    let editors = $(ele).edatagrid('getEditors', index) || [];
    let dataRowsLength = ($(ele).edatagrid('getRows') || []).length;
    if (editors.length > 0) {
        for (let editor of editors) {
            if (editor.target != undefined) {
                let input;
                if (editor.type != 'checkbox') {
                    input = $(editor.target).textbox('textbox');
                } else {
                    input = $(editor.target);
                }
                input.bind('keydown', function (e) {
                    let editorField = editor.field;
                    if (e && (e.keyCode == 38 || e.keyCode == 40)) {
                        let i;
                        //  上键
                        if (e.keyCode == 38) {
                            i = index - 1;
                            if (i >= 0) {
                                $(ele).edatagrid('saveRow');
                                $(ele).edatagrid('selectRow', i);
                                $(ele).edatagrid('editRow', i);
                            }
                        }
                        //  下键
                        if (e.keyCode == 40) {
                            i = index + 1;
                            if (i < dataRowsLength) {
                                $(ele).edatagrid('saveRow');
                                $(ele).edatagrid('selectRow', i);
                                $(ele).edatagrid('editRow', i);
                            }
                        }
                        let ed = $(ele).edatagrid('getEditor', {index: i, field: editorField});
                        if (ed != undefined) {
                            if (ed.type != 'checkbox') {
                                $(ed.target).textbox('textbox').focus();
                                setTimeout(() => {
                                    $(ed.target).textbox('textbox').select();
                                }, 300)
                            } else {
                                $(ed.target).focus();
                            }
                        }
                    }
                })
            }
        }
    }
}

/**
 * 基础资料导出Excel
 * @param ele       datagrid选择器
 * @param fileName  导出文件名
 */
function exportExcel(ele, fileName) {
    $.messager.progress({
        title: '提示',
        msg: '生成中,请稍候...',
        interval: 5000
    });
    try {
        let data = $(ele).datagrid('getFormatRows') || [];
        let columns = $(ele).datagrid('options').columns[0].filter(item => item['hidden'] == undefined || item['hidden'] == false);
        let newColumns = new Map();
        let newFields = new Map();
        for (let i = 0; i < columns.length; i++) {
            newColumns.set(i, columns[i]['title']);
            newFields.set(i, columns[i]['field']);
        }
        let dataSource = data.map(item => {
            let j = {};
            newFields.forEach((value, key) => {
                j[key] = item[value] || '';
            });
            return j;
        });
        let view = {
            fileName: fileName,
            dataSource: [{
                sheetName: fileName,
                topic: fileName,
                columns: conventMapToObject(newColumns),
                data: dataSource
            }]
        };
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'file/export', true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhr.onload = function () {
            if (this.status == 200) {
                let url = window.URL.createObjectURL(this.response);
                let a = $('<a/>');
                a.attr('href', url);
                a[0].download = fileName + '.xlsx';
                a[0].click();
                a.remove();
            }
            $.messager.progress('close');
        };
        xhr.send(JSON.stringify(view));

        function conventMapToObject(map) {
            let obj = Object.create(null);
            for (let item of map.keys()) {
                obj[item] = map.get(item);
            }
            return obj;
        }
    } catch (e) {
        $.messager.progress('close');
        console.table(e);
    }
}